//
//  XcodeCleanHomeCell.swift
//  ZJTools
//
//  Created by 万孟超 on 2023/11/21.
//

import Cocoa
import SnapKit

class XcodeCleanHomeCell: NSTableCellView {

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        // Drawing code here.
    }
    
    var cleanBlock: ((Bool) -> ())?
    
    var title: String? {
        didSet {
            titleLabel.stringValue = title ?? ""
        }
    }
    
    var size: Double = 0 {
        didSet {
            sizeLabel.stringValue = size.size
        }
    }
    
    var isOn: Bool = false {
        didSet{
            offOnButton.state = isOn ? .on : .off
        }
    }
    
    lazy var backView = NSView()
    
    lazy var offOnButton: NSSwitch = {
       let bt = NSSwitch()
        bt.target = self
        bt.action = #selector(offOnChanged(_:))
        return bt
    }()
    
    lazy var titleLabel: NSTextField = {
        let tf = NSTextField()
        tf.isVerticalCenter = true
        tf.font = .systemFont(ofSize: 12)
        tf.isBordered = false
        tf.isEditable = false
        tf.textColor = .black
        tf.bezelStyle = .roundedBezel
        return tf
    }()
    
    lazy var sizeLabel: NSTextField = {
        let tf = NSTextField()
        tf.isVerticalCenter = true
        tf.font = .systemFont(ofSize: 12)
        tf.isBordered = false
        tf.isEditable = false
        tf.textColor = .black
        tf.bezelStyle = .roundedBezel
        return tf
    }()
    
    override init(frame frameRect: NSRect) {
        super.init(frame: .zero)
        installSubview()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func installSubview() {
        
        addSubview(backView)
        backView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.top.equalTo(6)
            make.right.equalTo(0)
            make.bottom.equalTo(-6)
        }
        
        // 添加标题
        backView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.centerY.equalToSuperview()
        }
        
        backView.addSubview(offOnButton)
        offOnButton.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.centerY.equalToSuperview()
        }
        
        backView.addSubview(sizeLabel)
        sizeLabel.snp.makeConstraints { make in
            make.right.equalTo(offOnButton.snp.left).offset(-20)
            make.centerY.equalToSuperview()
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {[self] in
            backView.addGradientBackgroundColor(colors: [.randomColor(alpha: 0.3), .randomColor(alpha: 0.3), .randomColor(alpha: 0.3)], gradientType: .LeftToRight, radius: 8)
        }
    }
    
    @objc func offOnChanged(_ sender: NSButton) {
        cleanBlock?(sender.state == .on)
    }
}
